//Вторая лаба по jdbc
package dao;

import dao.bean.User;
import dao.dao.JdbcUtils;
import dao.dao.UserDaoJdbc;
import dao.exception.NotUniqueUserEmailException;
import dao.exception.NotUniqueUserLoginException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDaoGeneratedKeys {

    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            throw new ExceptionInInitializerError(e);
        }
    }

    private Connection getConnection() throws SQLException {
        // error: empty url - no driver
        // error: wrong db name
        return DriverManager.getConnection("jdbc:mysql://localhost:3306/production_eshop", "root", "2479");
    }

    public int insert(String login, String email) throws SQLException,
            NotUniqueUserLoginException, NotUniqueUserEmailException {
        int id = 0;
        Connection conn = getConnection();
        PreparedStatement ps = null;
        try {
            conn.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
            conn.setAutoCommit(false);

//            if (existWithLogin0(conn, user.getLogin())) {
//                throw new NotUniqueUserLoginException("Login '" + user.getLogin() + "' doubled");
//            }
//            if (existWithEmail0(conn, user.getEmail())) {
//                throw new NotUniqueUserEmailException("Email '" + user.getEmail() + "' doubled");
//            }

            ps = conn.prepareStatement("INSERT INTO User (login, email) VALUES (?, ?)");
            ps.setString(1, login);
            ps.setString(2, email);

            ps.executeUpdate();
            ResultSet rs = ps.executeQuery("Select LAST_INSERT_ID()");
            if (rs.next()) {
                id = rs.getInt(1);
            }
            conn.commit();
            return id;
        } catch (SQLException e) {
            JdbcUtils.rollbackQuietly(conn);
            throw e;
        } finally {
            JdbcUtils.closeQuietly(ps);
            JdbcUtils.closeQuietly(conn);
        }
    }

    public static void main(String[] args) throws SQLException, 
            NotUniqueUserLoginException, NotUniqueUserEmailException {

        UserDaoGeneratedKeys ud = new UserDaoGeneratedKeys();
        System.out.println("Last generated id: " + ud.insert("Rony", "rony@mail.com"));
    }
}
